<?php
/**
 * Created by PhpStorm.
 * User: xh
 * Date: 2019/12/16
 * Time: 2:20 PM
 */

namespace weChat\pay;


class Notify extends Pit
{
    /** 微信支付通知处理
     * @param array $notifyInfo
     * @param string $returnString
     * @return bool
     */
    public function handle(array &$notifyInfo, string &$returnString)
    {
        $xml = file_get_contents("php://input");
        $this->xmlLog($xml);
        $data = [];
        $res = $this->toArray($xml, $data);
        if (empty($res)) {
            $returnString = $this->reply('FAIL', '没有数据返回！');
            return false;
        }
        if (!is_array($data) || !array_key_exists('return_code', $data)) {
            $this->errorLog($xml, '输入数据存在异常！');
            $returnString = $this->reply('FAIL', '输出数据存在异常!');
            return false;
        }
        if ($data['return_code'] != 'SUCCESS') {
            $this->errorLog($xml,'返回状态码非SUCCESS，错误信息:' . $data['return_msg']);
            return false;
        }
        //验证签名
        if ($this->checkSign($data, $xml, $returnString)) {
            $notifyInfo = $data;
            return true;
        }
        return false;
    }

    /** 验证签名
     * @param array $data
     * @param string $xml
     * @param string $returnString
     * @return bool
     */
    protected function checkSign(array $data, string $xml, string &$returnString): bool
    {
        if (!array_key_exists('sign', $data)) {
            $this->errorLog($xml, '输入数据存在异常！');
            $returnString = $this->reply('FAIL', '签名错误!');
            return false;
        }
        $signType = empty($data['sign_type']) ? $this->signType : $data['sign_type'];
        $sign = $this->sign($data, $signType);
        if ($data['sign'] != $sign) {
            $this->errorLog($xml, '签名错误！');
            $returnString = $this->reply('FAIL', '签名错误!');
            return false;
        } else {
            $returnString = $this->reply('SUCCESS', 'ok');
            return true;
        }
    }
}